package com.jxd.project.travel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jxd.project.travel.dao.IDictionaryDao;
import com.jxd.project.travel.model.Dictionary;
import com.jxd.project.travel.service.IDictionaryService;
import com.jxd.project.travel.dao.IDictTypeDao;
import com.jxd.project.travel.model.DictType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName TransportationImpl
 * @Description TODO
 * @Author 邢子剑
 * @Date 2025/9/24 上午9:21
 * @Version 1.0
 */
@Service
public class DictionaryImpl extends ServiceImpl<IDictionaryDao, com.jxd.project.travel.model.Dictionary> implements IDictionaryService {
    @Autowired
    private IDictionaryDao dictionaryDao;

    @Autowired
    private IDictTypeDao dictTypeDao;

    /**
     * 获取全部出行方式
     * @return
     */
    @Override
    public List<Map<Integer, String>> getTransportation() {
        LambdaQueryWrapper<com.jxd.project.travel.model.Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(com.jxd.project.travel.model.Dictionary::getType, "交通工具");

        List<com.jxd.project.travel.model.Dictionary> list = dictionaryDao.selectList(queryWrapper);
        List<Map<Integer, String>> result = new ArrayList<>();
        for (com.jxd.project.travel.model.Dictionary dictionary : list) {
            Map<Integer, String> map = Collections.singletonMap(dictionary.getId(), dictionary.getName());
            result.add(map);
        }
        return result;
    }

    /**
     * 获取全部审批状态
     *
     * @return
     */
    @Override
    public List<Map<String, String>> getApproval() {
        LambdaQueryWrapper<com.jxd.project.travel.model.Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(com.jxd.project.travel.model.Dictionary::getType, "审核流程");

        List<com.jxd.project.travel.model.Dictionary> list = dictionaryDao.selectList(queryWrapper);
        List<Map<String, String>> result = new ArrayList<>();
        for (com.jxd.project.travel.model.Dictionary dictionary : list) {
            Map<String, String> map = Collections.singletonMap(dictionary.getValue(), dictionary.getName());
            result.add(map);
        }
        return result;
    }

    /**
     * 获取指定id字典内容
     * @param id
     * @return
     */
    @Override
    public com.jxd.project.travel.model.Dictionary getOne(int id) {
        LambdaQueryWrapper<com.jxd.project.travel.model.Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(com.jxd.project.travel.model.Dictionary::getId, id);
        return dictionaryDao.selectOne(queryWrapper);
    }

    /**
     * 添加出行方式(可用于所有字典表中数据添加)
     * @param dictionary
     * @return
     */
    @Override
    public int add(com.jxd.project.travel.model.Dictionary dictionary) {
        return dictionaryDao.insert(dictionary);
    }

    @Override
    public List<com.jxd.project.travel.model.Dictionary> getAllDictionary(String type) {
        LambdaQueryWrapper<com.jxd.project.travel.model.Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(com.jxd.project.travel.model.Dictionary::getType, type);
        return dictionaryDao.selectList(queryWrapper);
    }

    @Override
    @Transactional
    public boolean saveDictionary(int id, String type, List<com.jxd.project.travel.model.Dictionary> newList) {

        // 先处理 dicttype 表
        DictType dictType = dictTypeDao.selectOne(
                new QueryWrapper<DictType>().eq("id", id)
        );
        if (dictType == null) {
            // 不存在则插入新的类型
            dictType = new DictType();
            dictType.setType(type);
            dictType.setIsdelete(0);
            dictTypeDao.insert(dictType);
        } else {
            // 若已存在
            dictType.setType(type);
            dictTypeDao.updateById(dictType);
        }

        // 2.1 查询该类型下所有【未被逻辑删除】的现有记录
        List<com.jxd.project.travel.model.Dictionary> existingList = dictionaryDao.selectList(
                new QueryWrapper<com.jxd.project.travel.model.Dictionary>().eq("type", type)
                // MyBatis-Plus会自动添加条件：AND is_delete = 0（未删除）
        );


        // 2.2 提取新列表中的所有ID（用于对比）
        Set<Integer> newIds = newList.stream()
                .filter(dict -> dict.getId() != 0) // 过滤未生成ID的新记录
                .map(com.jxd.project.travel.model.Dictionary::getId)
                .collect(Collectors.toSet());


        // 2.3 找出需要逻辑删除的记录：现有记录中ID不在新列表中的
        List<Integer> deleteIds = existingList.stream()
                .filter(existing -> !newIds.contains(existing.getId()))
                .map(com.jxd.project.travel.model.Dictionary::getId)
                .collect(Collectors.toList());


        // 2.4 批量逻辑删除这些记录（更新isDelete=1）
        if (!deleteIds.isEmpty()) {
            QueryWrapper<com.jxd.project.travel.model.Dictionary> deleteEntity = new QueryWrapper<>();
            deleteEntity.in("id", deleteIds);
            this.remove(deleteEntity);
        }

        for (Dictionary dict : newList) {
            dict.setType(type); // 确保类型一致
            dict.setIsDelete(0);
            if (dict.getId() == 0 || dictionaryDao.selectById(dict.getId()) == null) {
                // ID不存在：新增
                dictionaryDao.insert(dict);
            } else {
                // ID存在：更新
                dictionaryDao.updateById(dict);
            }
        }
        return true;
    }




}
